import { TOKEN } from "../config";
import { isObj } from "./util";

type Heade =
  | "application/x-www-form-urlencoded"
  | "application/json"
  | undefined;
type HReq<T> = (op: T) => T;

interface Options {
  method: "GET" | "POST" | "DELETE" | "PUT";
  url: string;
  data: any;
  header: { [par: string]: string; "content-type": string };
  success: (res: Res) => void;
  fail: (err: any) => void;
  complete: () => void;
}
interface Res {
  cookies: Array<string>;
  data: { [p: string]: any };
  errMsg: string;
  header: object;
  statusCode: number;
}

export class Req {
  //new Req()传入基值
  constructor(public url: string) {}
  //请求拦截器
  static handleReq?: HReq<Options>;
  //响应拦截器
  static handleRes?: (p: Res) => any;
  //失败处理
  static handleErr?: (e: any) => void;
  //模板
  requst(
    method: "GET" | "POST" | "DELETE" | "PUT",
    path: string,
    data: any,
    hd?: string
  ) {
    return new Promise((resolve) => {
      let options = {
        method,
        url: this.url + path,
        data,
        header: {
          "content-type": hd || "application/x-www-form-urlencoded",
        },
        success(res: any) {
          res = (Req.handleRes && Req.handleRes(res)) || res;
          resolve(res);
        },
        fail(err: any) {
          (Req.handleErr && Req.handleErr(err)) || console.log(err);
        },
        complete() {
          wx.hideLoading();
        },
      };
      options = (Req.handleReq && Req.handleReq(options)) || options;
      wx.showLoading({
        title: "请求数据中",
      });
      wx.request(options);
    });
  }
  /**
   *
   * @fun 重载
   */
  get(path: string, data?: object) {
    return this.requst("GET", path, data);
  }
  delete(path: string, data?: object) {
    return this.requst("DELETE", path, data);
  }
  post(path: string, data?: object, hdeade?: Heade) {
    return this.requst("POST", path, data, hdeade);
  }
  put(path: string, data?: object, hdeade?: Heade) {
    return this.requst("PUT", path, data, hdeade);
  }
}

//请求拦截器
Req.handleReq = (options) => {
  options.header.Authorization = wx.getStorageSync(TOKEN) || "none";
  return options;
};
//响应拦截器
Req.handleRes = (res) => {
  if (isObj(res.data.message)) {
    wx.setStorageSync(TOKEN, res.data.message.token || "null");
  }
  return res.data;
};
